import arrow

from rest_framework_mongoengine import serializers

from models.audit_log import AuditLog
from wass.display import (
    MODULE_NAME_DICT,
    SUBMODULE_NAME_DICT,
    ACTION_NAME_DICT,
    LOGIN_ACTION_DICT,
    LOGIN_RET_DICT,
    LOGIN_MODULE,
)


class OperationLogSerializer(serializers.DocumentSerializer):
    """操作日志序列化器"""

    class Meta:
        model = AuditLog
        # exclude = ["_cls"]

    def to_representation(self, instance):
        data = super().to_representation(instance)
        result = {
            "ip": data.get("ip", '-'),
            "operator": data.get("operator", ''),
            "source": data.get("source", '-'),
            "group": data.get('group', []),
            'module': data.get('module', '-'),
            'type': data.get('type', '-'),
        }
        if data.get("module") == LOGIN_MODULE:
            result["module"] = "登录"
            result["status"] = LOGIN_RET_DICT.get(data.get("status"), "-")
            result["type"] = LOGIN_ACTION_DICT.get(data.get("type"), "-")
            result["desc"] = data.get("desc", {}).get("detail", "")
        else:
            result["module"] = MODULE_NAME_DICT.get(data.get("module"), "-")
            result["type"] = SUBMODULE_NAME_DICT.get(data.get("type"), "-")
            result["action"] = ACTION_NAME_DICT.get(data.get("action"), "-")
            result["domain"] = data.get("domain") or "-"
            result["property_name"] = data.get("property_name") or "-"
            result["desc"] = data.get("desc", {})
        try:
            handle_time = arrow.get(instance.time).isoformat()
        except TypeError:
            handle_time = "-"
        result["time"] = handle_time
        return result
